package com.learnyou.server.xingzuo.dao.repository.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learnyou.server.xingzuo.dao.repository.entity.Storage;
import com.learnyou.server.xingzuo.dao.repository.mapper.StorageMapper;
import com.learnyou.server.xingzuo.dao.repository.service.IStorageService;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class StorageServiceImpl extends ServiceImpl<StorageMapper, Storage> implements IStorageService {
    @Override
    public Storage getStorageByKey(String storageKey) {
        return baseMapper.getStorageByKey(storageKey);
    }

    @Override
    public Storage upsertStorage(String storageKey, String storageValue) {
        Storage storage = getStorageByKey(storageKey);
        int affectedRows = 0;
        if (Objects.isNull(storage)) {
            storage = new Storage();
            storage.setStorageKey(storageKey);
            storage.setStorageValue(storageValue);
            affectedRows = baseMapper.insert(storage);
        } else {
            storage.setStorageValue(storageValue);
            affectedRows = baseMapper.updateById(storage);
        }
        return affectedRows == 1? storage: null;
    }
}
